package com.adwhirl.adapters;

import android.app.Activity;
import android.content.Context;
import android.util.Log;

import com.adwhirl.AdWhirlLayout;
import com.adwhirl.AdWhirlTargeting;
import com.adwhirl.AdWhirlLayout.ViewAdRunnable;
import com.adwhirl.obj.Ration;
import com.adwhirl.util.AdWhirlUtil;

import de.madvertise.android.sdk.MadvertiseUtil;
import de.madvertise.android.sdk.MadvertiseView;
import de.madvertise.android.sdk.MadvertiseView.MadvertiseViewCallbackListener;

public class MadvertiseAdapter extends AdWhirlAdapter implements MadvertiseViewCallbackListener {

    private MadvertiseView mMadvertiseView;
    
    public MadvertiseAdapter(AdWhirlLayout adWhirlLayout, Ration ration) {
        super(adWhirlLayout, ration);
    }

    @Override
    public void handle() {

        final AdWhirlLayout adWhirlLayout = adWhirlLayoutReference.get();
        if (adWhirlLayout == null) {
          return;
        }
        
        final Activity activity = adWhirlLayout.activityReference.get();
        if (activity == null) {
          return;
        }
                
        final Context context = activity.getApplicationContext();
        
        if(AdWhirlTargeting.getGender().equals(AdWhirlTargeting.Gender.MALE)) {
        MadvertiseUtil.setGender("M");
        } else if(AdWhirlTargeting.getGender().equals(AdWhirlTargeting.Gender.FEMALE)) {
            MadvertiseUtil.setGender("F");
        }
        
        if(AdWhirlTargeting.getAge() != 0) {
            MadvertiseUtil.setAge(Integer.toString(AdWhirlTargeting.getAge()));
        }
        
        mMadvertiseView = new MadvertiseView(context);
        mMadvertiseView.setMadvertiseViewCallbackListener(this);
    }
    
    private void adRequestFailed() {
        Log.d(AdWhirlUtil.ADWHIRL, "madvertise failure");     
        mMadvertiseView.setMadvertiseViewCallbackListener(null);
        AdWhirlLayout adWhirlLayout = adWhirlLayoutReference.get();
        if (adWhirlLayout == null) {
          return;
        }
        adWhirlLayout.rollover();
    }

    @Override
    public void onLoaded(boolean succeed, MadvertiseView madView) {
        if(succeed) {
            final AdWhirlLayout adWhirlLayout = adWhirlLayoutReference.get();
            if (adWhirlLayout == null) {
              return;
            }
            
            adWhirlLayout.adWhirlManager.resetRollover();
            adWhirlLayout.handler.post(new ViewAdRunnable(adWhirlLayout, mMadvertiseView));
            adWhirlLayout.rotateThreadedDelayed();
        } else {
            adRequestFailed();
        }
    }
    
    @Override
    public void onError(Exception exception) {      
        adRequestFailed();
    }

    @Override
    public void onIllegalHttpStatusCode(int statusCode, String message) { 
        adRequestFailed();
    }

}
